package longshu.srpc.server.impl;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import longshu.srpc.api.RpcRequest;
import longshu.srpc.api.RpcResponse;
import longshu.srpc.api.RpcService;
import longshu.srpc.server.RpcProcessor;

import java.lang.reflect.Method;

@Slf4j
public class SimpleRpcProcessor implements RpcProcessor {
    @Setter
    private SimpleRpcServer rpcServer;

    @Override
    public RpcResponse process(RpcRequest rpcRequest) {
        log.debug("rpcRequest:{}", rpcRequest);
        String serviceName = rpcRequest.getServiceName();
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();

        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setRequestId(rpcRequest.getRequestId());

        RpcService rpcService = rpcServer.getRpcService(serviceName);
        log.debug("rpcService:{}", rpcService);
        if (rpcService == null) {
            rpcResponse.setError("Not Found:" + serviceName);
            return rpcResponse;
        }

        try {
            Method method = rpcService.getClass().getMethod(methodName, parameterTypes);
            Object result = method.invoke(rpcService, parameters);
            rpcResponse.setResult(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            rpcResponse.setError(String.valueOf(e.getMessage()));
        }
        log.debug("rpcResponse:{}", rpcResponse);
        return rpcResponse;
    }

}
